/*
 *  src/mm/mm_allocate.c
 *
 *  Harry Wei <harryxiyou@gmail.com> (C) 2011
 */
#include <glib.h>
#include <stdio.h>
#include <string.h>

#include "mm.h"

int mm_allocate(struct mm_ctrl *ctrl, uint32_t start_addr, 
			uint32_t size, const char *process_name)
{
	g_message("enter func %s...", __func__);
	if (NULL == ctrl || (size > ctrl->free_size) ||
		(start_addr < ctrl->start_addr) || (start_addr > ctrl->end_addr)) {
		g_message("%s -- ctrl is null || parameter error! || no enough free memory", __func__);
		return -1;
	}
	struct allocate_section *allocate = (struct allocate_section *)g_malloc0(sizeof(struct allocate_section));
	if (NULL == allocate) {
		g_message("%s -- allocate allocate error!", __func__);
		return -1;
	}
	allocate->size = size;
#if 0
	//TODO Now it is only, i will do nf, bf, wf...
	allocate->start_addr = mm_ff(ctrl, size);
	if (-1 == allocate->start_addr) {
		g_message("%s -- mm_ff error!", __func__);
		return -1;
	}
#endif
	allocate->start_addr = start_addr;
	allocate->end_addr = allocate->start_addr + size - 1;
	memset(allocate->process_name, 0, PROCESS_NAME_LEN);
	g_strlcpy(allocate->process_name, process_name, PROCESS_NAME_LEN);
	if (NULL == ctrl->cur_allocate_handler) {
		allocate->pid = 0;
	} else {
		allocate->pid = ctrl->cur_allocate_handler->pid + 1;
	}
	//update the ctrl
	ctrl->allocate_size += size;
	ctrl->free_size -= size;
	ctrl->process_nums += 1;
	if (NULL == ctrl->allocate_head) {
		ctrl->allocate_head = allocate;
	} else {
		ctrl->cur_allocate_handler->next = allocate;
	}
	ctrl->cur_allocate_handler = allocate;
	g_message("%s -- allocate success, leave...", __func__);
	return 0;
}

